import React from 'react';
import ReactDOM from 'react-dom';
import { useEffect, useState } from "react";

interface modalControl {
  addChild: any;
  removeChild: any;
}
let modalControl: modalControl={
    addChild:null,
    removeChild:null,
};

type StateType = {
  nodeList: Array<{ id: number; config: any; node: any }>;
  activeIDList: Array<number>;
};

interface Message {
  state: StateType;
}
class Message extends React.Component {
  constructor(props: any) {
    super(props);
    this.state = {
      nodeList: [],
      activeIDList: [],
    };
    const addChild = async (item: any, config: any) => {
      let nodeNew = [...this.state.nodeList];
      let id = new Date().getTime();
      nodeNew.push({
        node: item,
        config,
        id,
      });
      let newActiveIDList = [...this.state.activeIDList, id];
      //给activeIDList添加这个id
      return new Promise<number>((resolve) => {
        /** setState的第二个参数是用于设置state值成功后的回调函数 */
        this.setState(
          {
            activeIDList: newActiveIDList,
            nodeList: nodeNew,
          },
          () => {
            console.log('item.node',this.state.nodeList[0].node);
            resolve(nodeNew.length - 1);
          }
        );
      });
    };
    const removeChild = async (key: any) => {
      let { config, id: nodeID } = this.state.nodeList[key];
      return new Promise<void>((resolve, reject) => {
        setTimeout(() => {
          let newActiveIDList = this.state.activeIDList.filter(
            (item) => item !== nodeID
          );
          this.setState({ activeIDList: newActiveIDList }, () => {
            let newNodeList = this.state.nodeList.filter(
              (item) => item.id !== nodeID
            );
            setTimeout(() => {
              this.setState({ nodeList: newNodeList }, () => {
                resolve();
              });
            }, config.duration);
          });
        }, config.delay);
      });
    };
    modalControl.addChild = addChild;
    modalControl.removeChild = removeChild;
  }

  componentDidMount() {}
  render() {
    return (
      <div className="Message-Wrapper">
          <div className="Message-inner">
        {this.state.nodeList.map((item, index) => (
          <ModalItem
            key={item.id}
            show={this.state.activeIDList.indexOf(item.id) !== -1}
            config={item.config}
            
          >
            {item.node}
          </ModalItem>
        ))}
        </div>
      </div>
    );
  }
}

function ModalItem(props: any) {
  const [show, setShow] = useState(props.show);
  console.log(props.children,'children');
  useEffect(() => {
    if (props.show === false) {
      setShow(false);
    }
  }, [props.show]);

  return (<div className={`modal-item ${show?"":"modal-item-hidden"}`}
    // style={{'--duration--':props.config.duration+"ms"}}
  >{props.children}</div>);
}

function MessageTemplate(props: any) {
  console.log('MessageTemplate',props);
  return (
    <div
      className="MessageTemplate-Wrapper"
      onClick={() => {
        console.log("test");
      }}
    >
      <span>{props.content}</span>
    </div>
  );
}
const defaultConfig = {
  delay: 1500,
  duration: 360,
};
async function message(props: { content: string; type: string }) {
  let key = await modalControl.addChild(
    <MessageTemplate content={props.content} type={props.type} />,
    defaultConfig
  );
  await modalControl.removeChild(key);
}

function messageConfig(e: any) {
  let options = {
    ...defaultConfig,
    ...e,
  };
  return async function (content: any) {
    let key = await modalControl.addChild(
      <MessageTemplate
        type={options.type}
        content={content || options.content}
      />,
      options
    );
    await modalControl.removeChild(key);
  };
}
(function initModalContainer() {
  console.log('执行了initModalContainer');
  let ele = document.getElementById("source-modal-contain");
  if (!ele) {
    //如果不存在容器，则进行创建
    let sourceModalContainer = document.createElement("div");
    sourceModalContainer.id = "source-modal-contain";
    document.body.append(sourceModalContainer);
    ele = document.getElementById("source-modal-contain");
    //通过ReactDOM将容器挂载在真实dom上
    ReactDOM.render(<Message />, ele);
  }
})();
 
export { message, messageConfig };
